package org.example.servlet;

import org.example.entity.Material;
import org.example.entity.User;
import org.example.other.ErrorEnum;
import org.example.other.ServiceException;
import org.example.service.MaterialService;
import org.example.service.impl.MaterialServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns = "/material/*")
public class MaterialServlet extends BaseServlet{
    MaterialService materialService;

    public MaterialServlet() {
        materialService = new MaterialServiceImpl();
    }
    @Override
    protected void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String requestURI = req.getRequestURI();
        switch (requestURI) {
            case "/material/save":
                save(req, resp);
                break;
            default:
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "资源未找到");
                break;
        }
    }

    private void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (!"管理员".equals(user.getRole())) {
            // 前端只有管理员的主页菜单有添加物资的菜单, 后端还有必须校验权限吗
            throw new ServiceException(ErrorEnum.PERMISSION_DENIED);
        }
        Material material = new Material();
        material.setMaterialName(req.getParameter("materialName"));
        material.setMaterialImage(req.getParameter("materialImage"));
        material.setStock(getIntegerParameter(req, "stock"));
        material.setWarningStock(getIntegerParameter(req, "warningStock"));
        materialService.save(material);
        // 业务层的save方法如果抛了异常, 父类会捕捉到, 返回业务异常的响应
        // 业务层的save方法如果没有异常, 给一个最简单的成功响应
        success(resp);
    }
}
